package com.example.leetdemo.finash;


import java.util.ArrayList;
import java.util.List;

public class Solution1367 {

    public boolean isSubPath(ListNode head, TreeNode root) {

        List<TreeNode> list = new ArrayList<>();
        list.add(root);
        while (list.size() > 0) {
            List<TreeNode> temp = new ArrayList<>();
            for (TreeNode treeNode : list) {
                if (treeNode.val == head.val) {
                    if (checkSubPath(treeNode, head)) {
                        return true;
                    }
                }
                if (treeNode.left != null) {
                    temp.add(treeNode.left);
                }
                if (treeNode.right != null) {
                    temp.add(treeNode.right);
                }
            }
            list = temp;
        }
        return false;
    }
    
    private boolean checkSubPath(TreeNode treeNode, ListNode listNode) {
        if (listNode.next == null) {
            return true;
        }
        ListNode next = listNode.next;
        boolean isLeftSub = false;
        boolean isRightSub = false;
        if (treeNode.left != null && treeNode.left.val == next.val) {
            isLeftSub = checkSubPath(treeNode.left, next);
        }
        if (treeNode.right != null && treeNode.right.val == next.val) {
            isRightSub = checkSubPath(treeNode.right, next);
        }
        return isLeftSub || isRightSub;
    }

    public class TreeNode {

        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
    

    public class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }
}
